package com.fivetalks.client;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ArrowFormActivity extends Activity implements Runnable,
		OnClickListener {

	LinearLayout subLayout;
	SurfaceView sfView;
	LinearLayout[] layoutUser = new LinearLayout[8];
	ImageButton btUser[] = new ImageButton[8];
	Builder dlg;
	TextView tvResult;
	ProgressBar pbTimer;
	Thread mThread;
	Thread nThread;
	Thread thread;
	static final int MAX = 15;
	public int partner;
	public long roomNumber;
	// public int position = 0;
	public int numMale = 0;
	public int numFemale = 0;
	String user;
	Bitmap bm;
	boolean block = true;
	long id;
	int position;
	boolean blocking = true;
	boolean block2 = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_arrow);

		Intent intent = getIntent();
		roomNumber = (Long) intent.getSerializableExtra("roomNumber");
		Log.d("roomNumber", roomNumber + "");

		partner = 0;

		for (int i = 0; i < layoutUser.length; i++) {
			layoutUser[i] = (LinearLayout) findViewById(getResources()
					.getIdentifier("user" + i, "id", getPackageName()));
		}
		start();
	}

	public void makeButton(final int numMale, final int numFemale) {

		nThread = new Thread(new Runnable() {

			public void run() {
				SocketClient sc = SocketClient.getInstance(null, null, null,
						null, ArrowFormActivity.this, null, null, null);
				try {
					sc.getDos().writeUTF("getPictures");
					sc.getDos().writeUTF(roomNumber + "");
					for (int i = 0; i < btUser.length; i++) {

						btUser[i] = new ImageButton(ArrowFormActivity.this);
						btUser[i].setId(i);
						btUser[i]
								.setLayoutParams(new LinearLayout.LayoutParams(
										LayoutParams.MATCH_PARENT,
										LayoutParams.MATCH_PARENT));
						layoutUser[i].addView(btUser[i]);

						if (numMale <= i && i < 4)
							btUser[i].setBackgroundResource(R.drawable.unknown);
						else if (i < 8 && 8 - (4 - numFemale) <= i)
							btUser[i].setBackgroundResource(R.drawable.unknown);
						else {
							sc.getDos().writeUTF(i + 1 + "");

							btUser[i]
									.setOnClickListener(ArrowFormActivity.this);

						}

					}
					if ("MALE".equals(sc.getGender()))
						unabledButton(sc.getGender(), numMale);

					else
						unabledButton(sc.getGender(), numFemale);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		nThread.start();
	}

	public void start() {
		mThread = new Thread(this);
		mThread.start();
		while (true) {
			if (numMale != 0 && numFemale != 0) { // 수정
				Log.d("numMale", numMale + "");
				Log.d("numFemale", numFemale + "");
				break;
			}
		}
		makeButton(numMale, numFemale);
		new TimerTask().execute(MAX);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_arrow, menu);
		return true;
	}

	class TimerTask extends AsyncTask<Integer, Integer, Integer> {

		protected void onPreExecute() {
			pbTimer = (ProgressBar) findViewById(R.id.pbTimer);
			pbTimer.setMax(MAX);
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			int num = params[0];
			while (num > 0) {
				try {
					num--;
					publishProgress(num);
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return num;
		}

		protected void onProgressUpdate(Integer... params) {
			pbTimer.setProgress(params[0]);
		}

		protected void onPostExecute(Integer result) {
			if (result == 0) {
				// Intent intent = new Intent(ArrowFormActivity.this,
				// ArrowResultActivity.class);
				// startActivity(intent);
				Log.d("여긴", "오잔아");
				// while (true) {
				// if (block) {
				subLayout = (LinearLayout) findViewById(R.id.sublayout);
				sfView = new ArrowResultView(ArrowFormActivity.this, roomNumber);
				Log.d("여기까지", "왔다네");
				subLayout.addView(sfView);
				unableButton();
				pbTimer.setVisibility(ProgressBar.GONE);
				tvResult = (TextView) findViewById(R.id.tvResult);
			}
		}
	}

	public void unabledButton(String sex, int num) // 동성들의 버튼을 비활성화 시킨다.
	{
		if ("MALE".equals(sex)) {
			for (int i = 0; i < num; i++)
				btUser[i].setEnabled(false);
		} else {
			for (int i = 4; i < num + 4; i++)
				btUser[i].setEnabled(false);
		}
	}

	public void unableButton() // 오버로딩 전체 버튼 비활성화 시킨다.
	{
		for (int i = 0; i < btUser.length; i++) {
			btUser[i].setEnabled(false);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)
			return true;
		else if (keyCode == KeyEvent.KEYCODE_HOME)
			return true;
		return true;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		SocketClient sc = SocketClient.getInstance(null, null, null, null,
				ArrowFormActivity.this, null, null, null);
		try {
			sc.getDos().writeUTF("getPeople");
			sc.getDos().writeUTF(roomNumber + "");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(final View v) {
		// TODO Auto-generated method stub
		nThread = new Thread(new Runnable() {
			public void run() {
				SocketClient sc = SocketClient.getInstance(null, null, null,
						null, ArrowFormActivity.this, null, null, null);
				try {
					sc.getDos().writeUTF("getUserName");
					sc.getDos().writeUTF(roomNumber + "");
					sc.getDos().writeUTF((v.getId()) + 1 + "");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// block
				// true;
			}
		});
		nThread.start();
		while (block) {

		}
		Toast.makeText(ArrowFormActivity.this, user, Toast.LENGTH_SHORT).show();
		partner = v.getId() + 1;
		dlg = new AlertDialog.Builder(ArrowFormActivity.this);
		dlg.setTitle("선택")
				.setMessage(user + "님이 맘에 드시나요?")
				.setIcon(R.drawable.ic_launcher)
				.setPositiveButton("NO", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						partner = 0;
						Toast.makeText(ArrowFormActivity.this, "취소하셨습니다.",
								Toast.LENGTH_SHORT).show();

					}
				})
				.setNegativeButton("YES",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								nThread = new Thread(new Runnable() {
									public void run() {
										SocketClient sc = SocketClient
												.getInstance(null, null, null,
														null,
														ArrowFormActivity.this,
														null, null, null);
										try {

											sc.getDos().writeUTF(
													"partnerSelection");
											sc.getDos().writeUTF(partner + "");
											// block =
											// true;
										} catch (IOException e) {
											// TODO
											// Auto-generated
											// catch
											// block
											e.printStackTrace();
										}
									}
								});
								nThread.start();
								Toast.makeText(ArrowFormActivity.this,
										"선택하셨습니다.", Toast.LENGTH_SHORT).show();
								unableButton();
							}
						}).show();
	}
}
